<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>动态表格</title>
	<style type="text/css">
		.table{
			width: 100%;
			border-collapse: collapse;
			/* text-align: center; */
		}
		.table td,
		.table tr{
			border-bottom: 1px solid #ccc;
			text-align: left;
			padding: 1 .5em;
		}
		.table tr > td{
			line-height: 2em;
		}
	</style>
</head>
<body>
	<div>用户信息管理</div>
	<!-- 按钮区 -->
	<div class="btns">
		<button id="btn_add">添加</button>
		<button id="btn_batch_delete">批量删除 </button>
	</div>
	<table class="table" id="tbl_user">
		<thead>
			<tr>
				<td>编号</td>
				<td>姓名</td>
				<td>性别</td>
				<td>出生日期</td>
				<td>操作</td>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>1</td>
				<td>moyu</td>
				<td>女</td>
				<td>1997-1-12</td>
				<td>
					<a href="删除" class="btn_del">删除</a>
					<a href="修改" class="btn_edit">修改</a>
				</td>
			</tr>
		</tbody>
	</table>
	<script type="text/javascript">
		var btn_add = document.querySelector("#btn_add")
		var tbl_user = document.querySelector("#tbl_user")
		var btn_dels = document.querySelectorAll(".btn_del")
		//删除
		tbl_user.children[1].onmouseover = function(event){
			var target = event.target;
			if(target.nodeName === "TD"){
				target.parentElement.style.background = "#ededed";
			}
		}
		tbl_user.children[1].onmouseout = function(event){
			var target = event.target;
			if(target.nodeName === "TD"){
				target.parentElement.style.background = "#ffffff";
			}
		}
		//使用代理来进行事件绑定
		tbl_user. children[1].onclick = function(event){
			var target = event.target;
			if(target.nodeName === "A"){
				switch(target.getAttribute("class")){
					case "btn_del":
						//将当前行删除
						target.parentElement.parentElement.remove();
						break;
					case "btn_edit":
						alert("修改");
						break;
				}
			}
			event.preventDefault();
		}
		/*
		Array.prototype.slice.call(btn_dels,0).forEach(function(item){
			item.onclick = function(event){

				
			}
		})
		*/
		//添加
		btn_add.onclick = function(event){
			//新建一行，插入到表格中
			var newTr = document.createElement("tr");
			newTr.innerHTML = `
			<td>1</td>
			<td>`+Math.round(Math.random()*10)+`</td>			
			<td>男</td>
			<td>1998-3-21</td>
			<td>
				<a href="#" class="btn_del">删除</a>
				<a href="#" class="btn_edit">修改</a>
			</td>
			`;
			//将新建行追加到tbody内
			tbl_user.children[1].append(newTr);
		}
	</script>
</body>
</html>